using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using ConfOrm.NH;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;

namespace ThunderJob.Persistence.Extensions
{
    public static class ConfigurationExtensions
    {
        public static void AddHbmMapping(this Configuration configuration, Mapper mapper, Type[] entities)
        {
            string serialize = Serialize(mapper.CompileMappingFor(entities));
            configuration.AddXml(serialize);
        }

        private static string Serialize(HbmMapping hbmElement)
        {
            var setting = new XmlWriterSettings { Indent = true };
            var serializer = new XmlSerializer(typeof(HbmMapping));
            using (var memStream = new MemoryStream(2048))
            using (var xmlWriter = XmlWriter.Create(memStream, setting))
            {
                serializer.Serialize(xmlWriter, hbmElement);
                memStream.Flush();
                memStream.Position = 0;
                using (var sr = new StreamReader(memStream))
                {
                    return sr.ReadToEnd();
                }
            }
        }

    }
}